package com.fingard.dsp.bank.directbank.hbc01;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.directbank.hsbc01.EnumDirType;
import com.fingard.dsp.bank.directbank.hsbc01.EnumTransMode;
import com.fingard.dsp.bank.directbank.hsbc01.HSBC01Base;
import com.fingard.dsp.bank.directbank.vbao02.cust.request.BatchPayRecRequest;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingleBat;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingleBat;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingleBat;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpReceiver;

/**
 * @author XueJy on 2018/9/19.
 * @version 1.0
 */
public class HBC01SinglePay extends HBC01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //511055915020
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail detail = new RetAtsSglDetail();
        String askNumber = p_req1908.singleDetail.askNumber;
        detail.reqSeqID = askNumber;
        StringBuilder tmpMsg = new StringBuilder();
        ReqBatPayRec batPay = new ReqBatPayRec(p_req1908);
        writePayCommonHeader(tmpMsg, batPay);
        ReqBatPayRec re = new ReqBatPayRec(p_req1908);
        writePayBodyParams(tmpMsg, re);

        String path = getCommonDataFileDirectory(new Date(), "HSHBC") + File.separator + "batchPay";
        String filename = askNumber + ".txt";
        String filePath = path + File.separator + filename;
        FileHelper.writeFile(filePath, tmpMsg.toString(), getCharset());
        HSBC01Base hsbc01Base = new HSBC01Base();
        hsbc01Base.bankFront = this.bankFront;
        hsbc01Base.reqHeader = this.reqHeader;
        hsbc01Base.sbLog = this.sbLog;
        FtpReceiver ftpReceiver = hsbc01Base.sendToBank(filePath, filename, EnumTransMode.SinglePayForHS.getValue());
//      FtpReceiver ftpReceiver = sendToBank(filePath, filename);
        detail.respCode = "0";
        if (ftpReceiver.isCompleted) {
            detail.respInfo = "支付文件上传成功";
            detail.transState = "Uploaded";
            detail.payInfoCode = "Uploaded";
        } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
            detail.respInfo = ftpReceiver.connState;
            detail.transState = "BatchFailed";
            detail.payInfoCode = "BatchFailed";
        } else {
            detail.respCode = "-1";
            detail.respInfo = ftpReceiver.connMsg;
        }
        retAts.writeRetDetail(detail);
        return retAts;
    }

    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        String actNum = p_req1944.payAct;
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        retDetail.reqSeqID = p_req1944.askNumber;
        HSBC01Base hsbc01Base = new HSBC01Base();
        hsbc01Base.bankFront = this.bankFront;
        hsbc01Base.reqHeader = this.reqHeader;
        hsbc01Base.sbLog = this.sbLog;
        //中德安联个性化下载. 从中德提供的FTP下载
        FtpReceiver ftpReceiver = hsbc01Base.downloadFile();
//      FtpReceiver ftpReceiver = hsbc01Base.downFromHF();
        if (ftpReceiver != null) {
            if (ConnState.FAIL.equals(ftpReceiver.connState) || (!ftpReceiver.isCompleted && !"file not exists".equals(ftpReceiver.connState))) {
                retDetail.respInfo = ftpReceiver.connState + "+" + ftpReceiver.connMsg;
                retDetail.respCode = "-1";
                retAts.writeRetDetail(retDetail);
                return retAts;
            }
        }
        //String ackPath = hsbc01Base.getReceivePath("payack", p_req1944.getBgnDateTime());
        //恒生单笔付ACK和汇丰批量付ACK文件相同
        String ackPath = hsbc01Base.getReceivePath(EnumDirType.PayAck.getValue(), p_req1944.getBgnDateTime());
        List<String> filenames = getDirectoryAllFileName(ackPath);
        String batchNo = p_req1944.askNumber;
        //是否有ack文件
        boolean ackFlag = false;
        String refusedMessage = "";
        for (String filename : filenames) {
            if (!filename.contains(batchNo)) {
                continue;
            }
            String contain = "";
            synchronized (this) {
                //读取文件内容
                contain = FileHelper.readFileText(ackPath + File.separator + filename, getCharset());
            }
            WriteBankLogLn("回盘ACK文件内容:\n" + contain);
            String[] ackres = contain.split("\n");
            String[] ackhead = ackres[0].split(",");
            if (ackhead.length > 16 && ackhead[2].trim().equals(batchNo)) {
                ackFlag = true;
                if ("RECEIVED BY BANK".equals(ackhead[16].trim())) {
                    retDetail.respCode = "0";
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(Format.Date10Format.parse(p_req1944.bgnDate.substring(0, 10)));
                    String tmpMsg = "";
                    String[] body = ackres[2].split(",");
                    if (body.length > 14) {
                        tmpMsg = body[14].trim();
                    }
                    if (!"VALID PAYMENT".equals(tmpMsg)) {
                        retDetail.respInfo = tmpMsg;
                        retDetail.respCode = "0";
                        retDetail.transState = tmpMsg;
                        retDetail.payInfoCode = tmpMsg;
                        retAts.writeRetDetail(retDetail);
                        return retAts;
                    }
                    //时间
                    long nowTimeMillis = System.currentTimeMillis();
                    String actmap = getBankConfig().getMapValueByKey("ReportActMapping", actNum);
                    if (actmap != null && !"".equals(actmap)) {
                        actNum = actmap;
                    }
                    do {
                        String datePath = hsbc01Base.getReceivePath(EnumDirType.MT942.getValue(), cal.getTime());
                        //String datePath = hsbc01Base.getReceivePath("MT942", cal.getTime());
                        //被筛选文件
                        List<String> allDetailsFileNames = getDirectoryAllFileName(datePath);
                        //筛选结果文件
                        List<String> detailsFileNames = new ArrayList<String>();
                        for (String fileName : allDetailsFileNames) {
                            //MT942CN.EJ321.071910135852.088251418011.TXT
                            if (fileName.split("\\.")[3].equals(p_req1944.payAct)) {
                                detailsFileNames.add(fileName);
                            }
                        }


                        for (String fileName : detailsFileNames) {
                            try {
                                String alltext = FileHelper.readFileText(getTrimPath(datePath) + File.separator + fileName, getCharset());
                                //对单个文件进行解析查找对应的账号明细信息 //"H", 明细头记录拆分符
                                String spliter = "\n";
                                if (alltext.contains("\r\n")) {
                                    spliter = "\r\n";
                                }
                                //恒生发送的文件 账号 带-     :25:511-055915-020 ALLIANZ CN LIFE INS
                                String actNumTmp = alltext.split(":25:")[1].split(spliter)[0];
                                if (actNumTmp.startsWith(actNum)) {
                                    WriteBankLogLn("结果MT942文件\r\n" + alltext);
                                    String[] txns = alltext.split(":86:");
                                    if (txns.length > 1) {
                                        for (int i = 1; i < txns.length; i++) {
                                            String msg86 = txns[i];
                                            String[] msg86s = msg86.split(spliter);
                                            String custRef = msg86s[0];
                                            if (custRef.startsWith("TOTAL CHARGE")) {
                                                custRef = msg86s[1];
                                            }
                                            if (custRef.equals(batchNo)) {
                                                retDetail.respInfo = "交易成功";
                                                retDetail.respCode = "0";
                                                retDetail.transState = "S0000";
                                                retDetail.payInfoCode = "S0000";
                                                retAts.writeRetDetail(retDetail);
                                                return retAts;
                                            }
                                        }
                                    }
                                }
                            } catch (Exception ex) {
                                WriteBankLogLn("解析：" + fileName + " 文件异常：" + ex);
                            }
                        }
                        cal.add(Calendar.DAY_OF_YEAR, 1);
                        //查询小于当前时间,大于发送时间
                    } while (cal.getTimeInMillis() < nowTimeMillis);
                    //支付失败 不会产生报告,查询两天没有结果 则直接失败
                    if ("4".equals(p_req1944.payState)) {
                        p_req1944.payState = "5";
                    }
                    if (canBeNotExist(p_req1944, retDetail, 14400)) {
                        retDetail.respCode = "0";
                        retDetail.respInfo = "查询无记录";
                        retDetail.transState = PaymentState.FAIL_Payment;
                        retDetail.payInfoCode = "查询无记录";
                        retAts.writeRetDetail(retDetail);
                        return retAts;
                    } else {
                        retAts.writeRetDetail(retDetail);
                        return retAts;
                    }
                } else {
                    refusedMessage = ackhead[16].trim();
                }
            }
        }

        //如果找不到ACK文件则再次发送
        if (!ackFlag) {
            retDetail.respCode = "-1";
            retDetail.respInfo = "暂时无法查询到ACK文件,请稍后再试";
            retAts.writeRetDetail(retDetail);
            return retAts;
        } else {
            retDetail.respCode = "0";
            retDetail.respInfo = refusedMessage;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = refusedMessage;
            retAts.writeRetDetail(retDetail);
            return retAts;
        }
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
